import React, { useState } from 'react'
import { 
  List, 
  Grid, 
  NavBar,
  Avatar,
  Modal,
  Button,
  Checkbox
} from 'antd-mobile'
import {
  MessageOutline,
  FileOutline,
  UnorderedListOutline,
  UserOutline,
  CalendarOutline,
  LocationOutline,
  CouponOutline,
  LockOutline,
  PieOutline,
  ExclamationCircleOutline,
  FileOutline as FileTextOutline,
  SendOutline,
  MinusCircleOutline,
  SetOutline,
  RightOutline
} from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom'
import { getUsername, getUserAvatar } from '../../utils/userUtils'
import { hasValidToken } from '../../utils/auth'

function Ment() {
  const [name,setName] = useState('')
  const [showLoginModal, setShowLoginModal] = useState(false)
  const [agreedToPrivacy, setAgreedToPrivacy] = useState(true)
  const [isShaking, setIsShaking] = useState(false)

  // 组件加载时获取用户名
  React.useEffect(() => {
    const username = getUsername()
    setName(username)
  }, [])

  // 监听localStorage变化，实时更新用户信息
  React.useEffect(() => {
    const handleStorageChange = () => {
      const username = getUsername()
      setName(username)
    }

    // 监听storage事件（跨标签页同步）
    window.addEventListener('storage', handleStorageChange)
    
    // 定期检查localStorage变化（同标签页）
    const interval = setInterval(() => {
      const username = getUsername()
      if (username !== name) {
        setName(username)
      }
    }, 1000)

    return () => {
      window.removeEventListener('storage', handleStorageChange)
      clearInterval(interval)
    }
  }, [name])

  // 功能网格数据
  const featureGrid = [
    {
      icon: <MessageOutline style={{ color: '#1890ff', fontSize: '24px' }} />,
      text: '在线问诊',
      color: '#1890ff'
    },
    {
      icon: <FileOutline style={{ color: '#722ed1', fontSize: '24px' }} />,
      text: '健康档案',
      color: '#722ed1'
    },
    {
      icon: <UnorderedListOutline style={{ color: '#52c41a', fontSize: '24px' }} />,
      text: '用药建议',
      color: '#52c41a'
    },
    {
      icon: <UserOutline style={{ color: '#1890ff', fontSize: '24px' }} />,
      text: '优选订单',
      color: '#1890ff'
    },
    {
      icon: <UserOutline style={{ color: '#fa8c16', fontSize: '24px' }} />,
      text: '我的医生',
      color: '#fa8c16'
    },
    {
      icon: <CalendarOutline style={{ color: '#faad14', fontSize: '24px' }} />,
      text: '随访计划',
      color: '#faad14'
    }
  ]

  // 列表项数据
  const listItems = [
    { icon: <LocationOutline />, text: '收货地址' },
    { icon: <CouponOutline />, text: '我的卡券' },
    { icon: <LockOutline />, text: '门诊预约' },
    { icon: <PieOutline />, text: '价格公示' },
    { icon: <ExclamationCircleOutline />, text: '意见反馈' },
    { icon: <FileTextOutline />, text: '用户协议' },
    { icon: <SendOutline />, text: '隐私协议' },
    { icon: <MinusCircleOutline />, text: '关于我们' }
  ]

  // 处理功能点击
  const handleFeatureClick = (featureText: string) => {
    switch (featureText) {
      case '在线问诊': {
        // 检查是否有最新聊天的医生
        const lastChatDoctor = localStorage.getItem('lastChatDoctor')
        if (lastChatDoctor) {
          // 跳转到最新聊天的医生界面
          localStorage.setItem('selectedDoctor', lastChatDoctor)
        }
        // 直接跳转到message页面
        nav('/message')
        break
      }
      case '健康档案':
        nav('/health')
        break
      case '用药建议':
        nav('/medicine-advice')
        break
      case '优选订单':
        nav('/orders')
        break
      case '我的医生':
        nav('/concern')
        break
      case '随访计划':
        nav('/follow-up')
        break
      default:
        console.log('功能开发中:', featureText)
    }
  }

  // 点击用户区域：有token则不弹窗
  const handleUserAreaClick = () => {
    if (hasValidToken()) {
      return
    }
    setShowLoginModal(true)
  }

  // 处理暂不登录
/**
 * 处理未登录状态的回调函数
 * 当用户未登录时调用此函数来关闭登录模态框
 */
  const handleNotLogin = () => {
    setShowLoginModal(false) // 将登录模态框的状态设置为关闭
  }

  // 处理同意并登录
  const nav =useNavigate()
  /**
   * 处理用户同意隐私协议并登录的函数
   * 当用户勾选同意隐私协议后，执行登录相关操作
   */
  const handleAgreeAndLogin = () => {
    // 检查用户是否同意隐私协议
    if (agreedToPrivacy) {
      // 这里可以添加实际的登录逻辑
      console.log('用户同意隐私协议并登录')
      // 导航到登录页面
      nav('/login')
      // 关闭登录模态框
      setShowLoginModal(false)
      // 可以在这里设置登录状态
    } else {
      // 如果没有勾选，触发晃动动画
      triggerShakeAnimation()
    }
  }

  // 触发晃动动画
  const triggerShakeAnimation = () => {
    setIsShaking(true)
    // 动画结束后重置状态
    setTimeout(() => {
      setIsShaking(false)
    }, 600) // 动画持续600ms
  }

  // 处理隐私协议链接点击
  const handlePrivacyLink = (type: string) => {
    console.log(`点击了${type}链接`)
    // 这里可以添加跳转到具体协议页面的逻辑
  }

  return (
    <div style={{ backgroundColor: '#f5f5f5', minHeight: '100vh' }}>
      {/* 顶部导航栏 */}
      <NavBar 
        style={{ 
          backgroundColor: '#fff',
          borderBottom: '1px solid #f0f0f0'
        }}
      >
        我的
      </NavBar>

      {/* 用户登录区域 */}
      <div 
        style={{ 
          backgroundColor: '#fff', 
          padding: '20px 16px',
          marginBottom: '12px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          cursor: 'pointer'
        }}
        onClick={handleUserAreaClick}
      >
        <div style={{ display: 'flex', alignItems: 'center', flex: 1 }}>
          <Avatar 
            src={getUserAvatar() || ""}
            fallback="👤"
            style={{ 
              '--size': '60px',
              backgroundColor: '#e6f7ff',
              color: '#1890ff',
              fontSize: '24px'
            }}
          />
          <div style={{ marginLeft: '16px', flex: 1 }}>
            {name ? (
              <div style={{ 
                fontSize: '16px', 
                color: '#333',
                marginBottom: '4px'
              }}>
                欢迎，{name}
              </div>
            ) : (
              <div style={{ 
                fontSize: '16px', 
                color: '#333',
                marginBottom: '4px'
              }}>
                点击登录
              </div>
            )}
          </div>
          <RightOutline style={{ color: '#999' }} />
        </div>
        <SetOutline 
          style={{ 
            color: '#666', 
            fontSize: '20px',
            cursor: 'pointer',
            borderRadius: '50%',
            transition: 'all 0.3s ease'
          }} 
          onClick={(e) => {
            e.stopPropagation() // 阻止事件冒泡，避免触发登录弹窗
            nav('/settings')
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.backgroundColor = '#f0f0f0'
            e.currentTarget.style.color = '#1890ff'
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.backgroundColor = 'transparent'
            e.currentTarget.style.color = '#666'
          }}
        />
      </div>

      {/* 功能网格 */}
      <div style={{ 
        backgroundColor: '#fff', 
        padding: '16px',
        marginBottom: '12px'
      }}>
        <Grid columns={2} gap={12}>
          {featureGrid.map((item, index) => (
            <Grid.Item key={index}>
              <div 
                style={{
                  backgroundColor: '#fff',
                  borderRadius: '12px',
                  padding: '16px',
                  border: '1px solid #f0f0f0',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '12px',
                  minHeight: '60px',
                  cursor: 'pointer',
                  transition: 'all 0.3s ease'
                }}
                onClick={() => handleFeatureClick(item.text)}
                onMouseEnter={(e) => {
                  e.currentTarget.style.borderColor = item.color
                  e.currentTarget.style.boxShadow = `0 4px 12px ${item.color}20`
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.borderColor = '#f0f0f0'
                  e.currentTarget.style.boxShadow = 'none'
                }}
              >
                {item.icon}
                <span style={{ 
                  fontSize: '14px', 
                  color: '#333',
                  fontWeight: '500'
                }}>
                  {item.text}
                </span>
              </div>
            </Grid.Item>
          ))}
        </Grid>
      </div>

      {/* 列表项 */}
      <div style={{ backgroundColor: '#fff' }}>
        <List>
          {listItems.map((item, index) => (
            <List.Item
              key={index}
              prefix={item.icon}
              arrow={<RightOutline />}
              style={{
                fontSize: '14px',
                color: '#333'
              }}
              onClick={() => {
                if (item.text === '收货地址') {
                  nav('/address')
                } else {
                  console.log('功能开发中:', item.text)
                }
              }}
            >
              {item.text}
            </List.Item>
          ))}
        </List>
      </div>

      {/* 登录弹窗 */}
      <Modal
        visible={showLoginModal}
        content={
          <div style={{ 
            padding: '24px 20px',
            borderRadius: '16px',
            background: 'linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%)'
          }}>
            {/* 标题区域 */}
            <div style={{
              textAlign: 'center',
              marginBottom: '28px'
            }}>
              <div style={{
                fontSize: '20px',
                fontWeight: '700',
                color: '#1a1a1a',
                marginBottom: '8px'
              }}>
                请先登录
              </div>
              <div style={{
                fontSize: '14px',
                color: '#8c8c8c',
                lineHeight: '1.4'
              }}>
                登录后享受更多医疗服务
              </div>
            </div>
            
            {/* 按钮区域 */}
            <div style={{
              display: 'flex',
              flexDirection: 'column',
              gap: '12px',
              marginBottom: '24px'
            }}>
              <Button
                style={{
                  height: '48px',
                  borderRadius: '24px',
                  border: '2px solid #e8e8e8',
                  backgroundColor: '#ffffff',
                  color: '#595959',
                  fontSize: '16px',
                  fontWeight: '600',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
                  transition: 'all 0.3s ease'
                }}
                onClick={handleNotLogin}
              >
                暂不登录
              </Button>
              <Button
                style={{
                  height: '48px',
                  borderRadius: '24px',
                  background: 'linear-gradient(135deg, #1890ff 0%, #096dd9 100%)',
                  color: '#ffffff',
                  fontSize: '16px',
                  fontWeight: '600',
                  border: 'none',
                  boxShadow: '0 4px 16px rgba(24,144,255,0.3)',
                  transition: 'all 0.3s ease'
                }}
                onClick={handleAgreeAndLogin}
              >
                同意隐私协议并登录
              </Button>
            </div>
            
            {/* 隐私协议复选框 */}
            <div style={{
              display: 'flex',
              alignItems: 'flex-start',
              gap: '10px',
              padding: '16px',
              backgroundColor: '#fafafa',
              borderRadius: '12px',
              border: '1px solid #f0f0f0',
              // 添加晃动动画效果
              transform: isShaking ? 'translateX(0)' : 'translateX(0)',
              transition: isShaking ? 'none' : 'transform 0.3s ease',
              ...(isShaking && {
                animation: 'shake 0.6s ease-in-out'
              })
            }}>
              <Checkbox
                checked={agreedToPrivacy}
                onChange={(checked) => setAgreedToPrivacy(checked)}
                style={{ 
                  marginTop: '2px'
                }}
              />
              <div style={{
                fontSize: '13px',
                color: '#666',
                lineHeight: '1.6',
                flex: 1
              }}>
                <span style={{ color: '#8c8c8c' }}>已阅读并同意</span>
                <span 
                  style={{ 
                    color: '#1890ff', 
                    cursor: 'pointer',
                    textDecoration: 'underline',
                    fontWeight: '500',
                    transition: 'color 0.2s ease'
                  }}
                  onClick={() => handlePrivacyLink('妙手医生服务协议')}
                >
                  《妙手医生服务协议》
                </span>
                <span 
                  style={{ 
                    color: '#1890ff', 
                    cursor: 'pointer',
                    textDecoration: 'underline',
                    fontWeight: '500',
                    transition: 'color 0.2s ease'
                  }}
                  onClick={() => handlePrivacyLink('妙手医生隐私政策')}
                >
                  《妙手医生隐私政策》
                </span>
                <span style={{ color: '#8c8c8c' }}>及</span>
                <span 
                  style={{ 
                    color: '#1890ff', 
                    cursor: 'pointer',
                    textDecoration: 'underline',
                    fontWeight: '500',
                    transition: 'color 0.2s ease'
                  }}
                  onClick={() => handlePrivacyLink('妙手医生儿童个人信息保护规则')}
                >
                  《妙手医生儿童个人信息保护规则》
                </span>
              </div>
            </div>

            {/* 底部提示 */}
            <div style={{
              textAlign: 'center',
              marginTop: '16px',
              fontSize: '12px',
              color: '#bfbfbf'
            }}>
              登录即表示同意相关协议
            </div>
          </div>
        }
        closeOnMaskClick={false}
        onClose={() => setShowLoginModal(false)}
      />

      {/* 添加晃动动画的CSS样式 */}
      <style dangerouslySetInnerHTML={{
        __html: `
          @keyframes shake {
            0%, 100% { transform: translateX(0); }
            10%, 30%, 50%, 70%, 90% { transform: translateX(-8px); }
            20%, 40%, 60%, 80% { transform: translateX(8px); }
          }
        `
      }} />
    </div>
  )
}

export default Ment
